<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form :inline="true" ref="listQuery" :model="listQuery" class="demo-form-inline">
        <el-form-item prop="userId" label="用户">
          <User v-model="listQuery.userId" keyName="id" keyShow="name" placeholder="用户" title="用户查询" :disabled="useUserStore().organization.organizationType !== '1'" />
        </el-form-item>
        <el-form-item prop="title" label="标题">
          <el-input v-model="listQuery.title" placeholder="标题" @keyup.enter="handleFilter" />
        </el-form-item>
        <el-form-item prop="icon" label="图标">
          <el-input v-model="listQuery.icon" placeholder="图标" @keyup.enter="handleFilter" />
        </el-form-item>
        <el-form-item prop="name" label="名称">
          <el-input v-model="listQuery.name" placeholder="名称" @keyup.enter="handleFilter" />
        </el-form-item>
        <el-form-item prop="path" label="路径">
          <el-input v-model="listQuery.path" placeholder="路径" @keyup.enter="handleFilter" />
        </el-form-item>
        <el-form-item label="最后访问时间">
          <el-date-picker v-model="listQuery.lastVisitTimeRange"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          type="datetimerange"
                          range-separator="-"
                          start-placeholder="最后访问时间开始"
                          end-placeholder="最后访问时间结束" />
        </el-form-item>
        <el-form-item prop="click" label="访问次数">
          <el-input v-model="listQuery.click" placeholder="访问次数" @keyup.enter="handleFilter" />
        </el-form-item>
        <el-form-item>
          <el-button v-waves type="success" icon="Search" @click="handleFilter">
            查询
          </el-button>
          <el-button icon="Refresh" @click="handleResetQuery">
            重置
          </el-button>
          <!--
          <el-button v-show="checkAuthByCode('')" type="primary" icon="Edit" @click="handleAdd">
            新增
          </el-button>
          -->
          <el-button v-show="checkAuthByCode('')" type="primary" icon="Download" @click="handleExport">
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-divider class="el-divider--horizontal-margin" />
    <el-table v-loading="listLoading"
              :key="tableKey"
              :data="list"
              :row-style="{height: '0'}"
              :cell-style="{padding: '0'}"
              border
              fit
              highlight-current-row
              tooltip-effect="dark"
              @sort-change="handleSortChange"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="39px" />
      <el-table-column align="center" type="index" label="序号" width="60px" />
      <el-table-column v-if="isDebug" align="center" label="ID" prop="id" width="60px" sortable show-overflow-tooltip />
      <el-table-column align="center" label="用户" prop="userId" min-width="130px" sortable show-overflow-tooltip>
        <template v-slot="{row}"><LabelTag :foreignList="userList" :foreignIds="row.userId" :foreignLabel="'name'" /></template>
      </el-table-column>
      <el-table-column align="center" label="标题" prop="title" min-width="180px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.title }}</template>
      </el-table-column>
      <el-table-column align="center" label="图标" prop="icon" min-width="80px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.icon }}</template>
      </el-table-column>
      <el-table-column align="center" label="名称" prop="name" min-width="200px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.name }}</template>
      </el-table-column>
      <el-table-column align="center" label="路径" prop="path" min-width="80px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.path }}</template>
      </el-table-column>
      <el-table-column align="center" label="最后访问时间" prop="lastVisitTime" min-width="160px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.lastVisitTime }}</template>
      </el-table-column>
      <el-table-column align="center" label="访问次数" prop="click" min-width="120px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.click }}</template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" width="180px" prop="createTime" sortable show-overflow-tooltip>
        <template v-slot="{row}"><DateTag :timestamp="row.createTime" /></template>
      </el-table-column>
      <el-table-column align="center" label="最后修改时间" width="180px" prop="updateTime" sortable show-overflow-tooltip>
        <template v-slot="{row}"><DateTag :timestamp="row.updateTime" /></template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="160px" fixed="right">
        <template v-slot="{row}">
          <el-button type="primary" link @click="handleView(row)">查看</el-button>
          <!--
          <el-button v-show="checkAuthByCode('')" type="primary" link @click="handleEdit(row)">编辑</el-button>
          -->
          <el-popconfirm confirm-button-text="确定"
                         cancel-button-text="取消"
                         :icon="WarningFilled"
                         icon-color="#626AEF"
                         title="您确定删除么？"
                         @confirm="handleDelete(row)"
                         v-if="checkAuthByCode('') && row.userId === getUserId()">
            <template #reference>
              <el-button type="danger" link>删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-model:total="total" v-model:page="listQuery.pageNum" v-model:limit="listQuery.pageSize" @pagination="getList" />
    <el-dialog v-model="dialogVisible" :title="dialogTypeTitle" width="70%" top="2vh">
      <el-form class="my-form" ref="obj" :model="obj" :rules="rules" label-position="right" :disabled="dialogType === 'view'" label-width="auto">
        <el-form-item v-show="isDebug" label="ID">
          <text>{{ obj.id }}</text>
        </el-form-item>
        <el-form-item label="用户" prop="userId">
          <User v-model="obj.userId" keyName="id" keyShow="name" placeholder="用户" title="用户查询" />
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="obj.title" placeholder="请输入标题，最多输入100个字符" />
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-input v-model="obj.icon" placeholder="请输入图标，最多输入100个字符" />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="obj.name" placeholder="请输入名称，最多输入100个字符" />
        </el-form-item>
        <el-form-item label="路径" prop="path">
          <el-input v-model="obj.path" placeholder="请输入路径，最多输入100个字符" />
        </el-form-item>
        <el-form-item label="最后访问时间" prop="lastVisitTime">
          <el-date-picker v-model="obj.lastVisitTime" placeholder="请输入最后访问时间" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>
        <el-form-item label="访问次数" prop="click">
          <el-input v-model="obj.click" type="number" placeholder="请输入访问次数" />
        </el-form-item>
        <el-form-item label="创建时间">
          <text>{{ obj.createTime ? obj.createTime : '自动生成' }}</text>
        </el-form-item>
        <el-form-item label="最后修改时间">
          <text>{{ obj.updateTime ? obj.updateTime : '自动生成' }}</text>
        </el-form-item>
        <el-form-item v-show="isDebug" label="数据版本">
          <text>{{ obj.version }}</text>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="info" icon="Close" @click="dialogVisible=false">关闭</el-button>
        <el-button type="primary" icon="Check" v-show="dialogType !== 'view'" @click="doConfirm('obj')">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import baseConfig from '@/mixins/baseConfig'
import {doGet, doPost, doPut, doDelete, doGetDownload} from '@/config/http'
import {alertErrorMsg, customValidator, getListPageSize, notifySuccess} from '@/config/common'
import {getUserId} from "@/config/cookie";
import User from "@/views/components/base/selectUser.vue";
import useUserStore from "@/store/modules/user";
import initListStore from '@/store/modules/initList'

const emptyObj = {
  userId: null, // 用户表ID
  title: null, // 标题
  icon: null, // 图标
  name: null, // 名称
  path: null, // 路径
  lastVisitTime: null, // 最后访问时间
  click: null, // 访问次数
  id: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  deleted: null,
  version: null,
}

export default {
  name: 'userVisit_nocache',
  components: {User},
  mixins: [baseConfig],
  data() {
    return {
      svc: 'icims-api',
      obj: Object.assign({}, emptyObj),
      routes: [],
      dialogVisible: false,
      dialogType: 'add',
      dialogTypeTitle: '新增',
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: false,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        sortField: 'id',
        sortType: 'desc',
        userId: useUserStore().organization.organizationType !== '1' ? getUserId() : '',
        title: null,
        icon: null,
        name: null,
        path: null,
        lastVisitTimeStart: null,
        lastVisitTimeEnd: null,
        lastVisitTimeRange: [],//
        click: null,
        createTimeStart: null,
        createTimeEnd: null,
        updateTimeStart: null,
        updateTimeEnd: null,
      },
      selectionList: [],
      dialogFormVisible: false,
      dialogStatus: '',
      rules: {
        userId: [{ required: true, validator: customValidator, min: 1, max: 20, label: '用户表ID', trigger: ['blur', 'change'] }],
        title: [{ required: false, validator: customValidator, min: 0, max: 100, label: '标题', trigger: ['blur', 'change'] }],
        icon: [{ required: false, validator: customValidator, min: 0, max: 100, label: '图标', trigger: ['blur', 'change'] }],
        name: [{ required: false, validator: customValidator, min: 0, max: 100, label: '名称', trigger: ['blur', 'change'] }],
        path: [{ required: false, validator: customValidator, min: 0, max: 100, label: '路径', trigger: ['blur', 'change'] }],
        lastVisitTime: [{ required: false, validator: customValidator, min: 0, max: 20, label: '最后访问时间', trigger: ['blur', 'change'] }],
        click: [{ required: false, validator: customValidator, min: 0, max: 20, label: '访问次数', trigger: ['blur', 'change'] }],
      },
      userList: initListStore().userList,
      organizationList: initListStore().organizationList,
    }
  },
  computed: {
    routesData() {
      return this.routes
    }
  },
  created() {
    this.getList()
    // this.initList()
  },
  methods: {
    useUserStore,
    getUserId,
    // async initList() {
    //   let p1 = doGet(this.svc, '/user/page', {pageSize: getListPageSize()}, false)
    //   let p2 = doGet(this.svc, '/organization/page', {pageSize: getListPageSize()}, false)
    //   let resArray = await Promise.all([p1, p2])
    //   this.userList = resArray[0]['records']
    //   this.organizationList = resArray[1]['records']
    // },
    getList() {
      this.listLoading = true
      this.listQuery.lastVisitTimeStart = ''
      this.listQuery.lastVisitTimeEnd = ''
      if (this.listQuery.lastVisitTimeRange) {
        this.listQuery.lastVisitTimeStart = this.listQuery.lastVisitTimeRange[0]
        this.listQuery.lastVisitTimeEnd = this.listQuery.lastVisitTimeRange[1]
      }
      doGet(this.svc, '/user-visit/page', this.listQuery).then(res => {
        this.listLoading = false
        this.list = res['records']
        this.total = parseInt(res['total'])
      }).catch(e => {
        console.error(e)
        this.listLoading = false
      })
    },
    handleResetQuery() {
      this.resetForm("listQuery")
      this.listQuery.lastVisitTimeStart = ''
      this.listQuery.lastVisitTimeEnd = ''
      this.listQuery.lastVisitTimeRange = []
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    handleSelectionChange(data) {
      this.selectionList = data
    },
    handleSortChange(data) {
      const { prop, order } = data
      this.listQuery.sortField = prop
      this.listQuery.sortType = order === 'ascending' ? 'asc' : 'desc'
      this.handleFilter()
    },
    handleEdit(row) {
      this.dialogType = 'edit'
      this.dialogTypeTitle = '编辑'
      this.dialogVisible = true
      this.checkStrictly = true
      this.obj = Object.assign({}, row)
    },
    handleView(row) {
      this.dialogType = 'view'
      this.dialogTypeTitle = '详情'
      this.dialogVisible = true
      this.checkStrictly = false
      this.obj = Object.assign({}, row)
    },
    handleAdd() {
      this.dialogType = 'add'
      this.dialogTypeTitle = '新增'
      this.dialogVisible = true
      this.checkStrictly = true
      this.obj = Object.assign({}, emptyObj)
    },
    handleExport() {
      doGetDownload(this.svc, '/user-visit/export', this.listQuery)
    },
    handleDelete(row) {
      doDelete(this.svc, '/user-visit/' + row.id, {}).then(() => {
        notifySuccess('删除成功')
        this.getList()
        this.dialogVisible = false
      })
    },
    async doConfirm(formName) {
      let v = await this.$refs[formName].validate().catch((err)=>{return err})
      if (v !== true) {
        alertErrorMsg('表单验证不通过，请检查数据。')
        return
      }
      if (this.dialogType === 'edit') {
        doPut(this.svc, '/user-visit/modify', this.obj).then(() => {
          notifySuccess('修改成功')
          this.getList()
          this.dialogVisible = false
        })
      } else if (this.dialogType === 'add') {
        doPost(this.svc, '/user-visit/add', this.obj).then(() => {
          notifySuccess('新增成功')
          this.getList()
          this.dialogVisible = false
        })
      }
    },
  }
}
</script>
